package CompletableFuture_14;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

public class 基本异步任务_链式调用
{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 创建10个异步任务 - 使用Supplier而不是Callable
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            CompletableFuture.supplyAsync(new Supplier<String>() {
                        public String get() {
                            try {
                                Thread.sleep((long)(Math.random() * 500)); // 模拟耗时操作
                                return "任务" + taskId + "结果";
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }, executor)
                    .thenApply(new java.util.function.Function<String, String>() {
                        public String apply(String s) {
                            return s + " (已处理)";
                        }
                    })
                    .thenAccept(new java.util.function.Consumer<String>() {
                        public void accept(String s) {
                            System.out.println("处理完成: " + s);
                        }
                    })
                    .exceptionally(new java.util.function.Function<Throwable, Void>() {
                        public Void apply(Throwable t) {
                            System.out.println("任务失败: " + t.getMessage());
                            return null;
                        }
                    });
        }

        executor.shutdown();
    }
}